import React, { Component } from 'react'
import { StatusBar, RefreshControl, BackHandler, ActivityIndicator, View, ScrollView, Image, KeyboardAvoidingView } from 'react-native'
import ScrollableTabView, { ScrollableTabBar } from 'react-native-scrollable-tab-view'
import Icon from 'react-native-vector-icons/FontAwesome'
import AppConfig from '../Config/AppConfig'
const domain = AppConfig.domain
import { connect } from 'react-redux'

import { Loading, Empty } from '../Components'

import CommodityList from '../Components/CommodityList'

//import CommodityActions from '../Redux/CommodityRedux'

// Styles
import { Colors } from '../Themes'
import styles from './Styles/CommodityScreenStyle'

class CommodityScreen extends Component {
  static navigationOptions = {
    title: '实时发单',
    headerStyle: {elevation:0},
    tabBarLabel: '实时',
    tabBarIcon: ({tintColor}) =>
      <Icon name='clock-o' color={tintColor} size={24} />
  }
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    this.state = {
      refreshing: false,
      loading: true,
      failure: null,
      dataList: null,
      index: state.params ? state.params.initial : 0,
    }
  }
  getCommodityList(categoryId, isFreshing=false) {
    if (isFreshing) {
      this.setState({refreshing:true, failure:null})
    } else {
      this.setState({loading:true,failure:null})
    }
    const adcode = this.props.city ? this.props.city.adcode : null
    const url = `${domain}/api/index/project?category_id=${categoryId}&adcode=${adcode}`
    return fetch(url, {
      method: 'GET',
      headers: {
        Accept: 'application/json'
      }
    })
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          refreshing:false,
          loading:false,
          failure:false,
          dataList:responseJson.data})
      })
      .catch((error) => this.setState({
        refreshing:false,
        loading:false,
        failure:true}))
  }
  componentDidMount() {
    this._navListener = this.props.navigation.addListener('didFocus', ()=>{
      StatusBar.setTranslucent(false)
      StatusBar.setBarStyle('dark-content')
      StatusBar.setBackgroundColor('white')
    })
    const id = this.props.category.payload[this.state.index].id
    console.tron.log(id)
    this.getCommodityList(id)
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress)
  }
  componentWillUnmount() {
    this._navListener.remove();
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress)
  }
  componentDidUpdate(prevProps, prevState) {

    // for initial index
    if (prevProps.navigation.state !== this.props.navigation.state) {
      const index = this.props.navigation.state.params.initial
      this.setState({index:index})
    }

    // when category finished, get commodity list
    // if(prevProps.category.fetching
    //   && !this.props.category.fetching
    //   && this.props.category.payload) {
    //   const id = this.props.category.payload[this.state.index].id
    //   this.props.getCommodityList(id)
    // }

    // set category id start
    if(prevState.index !== this.state.index) {
      const id = this.props.category.payload[this.state.index].id
      this.getCommodityList(id)
    }

    // for refreshing
    //if(prevProps.commodity.fetching
    //  && prevState.refreshing
    //  && !this.props.commodity.error) {
    //  this.setState({refreshing:false})
    //}
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  onRefresh() {
    //this.setState({refreshing:true})
    const id = this.props.category.payload[this.state.index].id
    this.getCommodityList(id, true)
  }
  _setCategoryId = ({i}) => {
    this.setState({index:i})
  }
  render () {
    let commodityView = null
    if (this.state.loading) {
      commodityView = <Loading />
    } else if (this.state.failure) {
      commodityView = <Empty title='出错了' />
    } else if (!this.state.dataList) {
      commodityView = <Empty />
    } else {
      commodityView = (
        <CommodityList
          data={this.state.dataList}
          navigation={this.props.navigation} />
      )
    }
    return (
      <ScrollableTabView
        style={styles.container}
        onChangeTab={({i})=>this.setState({index:i})}
        page={this.state.index}
        tabBarBackgroundColor='white'
        tabBarActiveTextColor={Colors.primary}
        tabBarUnderlineStyle={{backgroundColor:Colors.primary,height:2}}
        renderTabBar={()=><ScrollableTabBar />}>
        {this.props.category.payload.map((item,i)=>
          item.name != '联盟酒店' && <ScrollView tabLabel={item.name} key={item.id}
            refreshControl={
              <RefreshControl
                refreshing={this.state.refreshing}
                onRefresh={this.onRefresh.bind(this)}
              />
            }>
            {commodityView}
          </ScrollView>
        )}
      </ScrollableTabView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    city: state.city.payload,
    category: state.commodityCategory
    //commodity: state.commodity,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    //getCommodityList: (categoryId) =>
    //  dispatch(CommodityActions.commodityRequest(categoryId)),
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CommodityScreen)
